package cn.abellflower.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * http工具类
 *
 * @author gbzdyf@126.com
 * @create 2018-07-03 15:20
 **/
public class HttpUtils {

    /**
     * client
     */
    private static final CloseableHttpClient client;
    private static final int SUCCESS_STATUS = 200;

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(3000).build();
        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }
    public static void main(String[] args) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("saleTaxNum", "339901999999109");
        map.put("fpqqlsh", "18071709523201000011");
        map.put("templateVersion", "1.0.0.6");
        map.put("sign", "46E3B98C28B73C354DB8C6E246774332816A85D14EF6A7D5D393339C636BBBE5FB4EE887B85078B6835D163BCE3D3186");
        map.put("clientVersion", "1.0.0.6");
        System.out.println(sendReq("http://127.0.0.1:18080/invoice/alone/getComponentKpInfo.do", map, ReqModeEnum.POST, CharSetEnum.UTF8));
    }

    /**
     * 发送请求
     * @param url
     * @param params
     * @param reqModeEnum
     * @return
     * @throws IOException
     */
    public static String sendReq(String url, Map<String, String> params, ReqModeEnum reqModeEnum, CharSetEnum charSetEnum) throws IOException {
        //封装
        int size = 0;
        if (null != params && !params.isEmpty()) {
            size = params.size();
        }

        final List<NameValuePair> pairs = new ArrayList<>(size);
        if (params != null && !params.isEmpty()) {
            params.forEach((k, v) -> {
                pairs.add(new BasicNameValuePair(k, v));
            });

        }
        String res = null;
        switch (reqModeEnum) {
            case GET:
                StringBuilder sb = new StringBuilder(url);
                if (!pairs.isEmpty()) {
                    sb.append(url).append("?").append(EntityUtils.toString(new UrlEncodedFormEntity(pairs), charSetEnum.getCharSet()));
                }
                res = executeReq(new HttpGet(sb.toString()), charSetEnum);
                break;
            case POST:
                HttpPost httpPost = new HttpPost(url);
                if (!pairs.isEmpty()) {
                    httpPost.setEntity(new UrlEncodedFormEntity(pairs, charSetEnum.getCharSet()));
                }
                res = executeReq(httpPost, charSetEnum);
                break;
            default:
                System.out.println("不做任何处理");
        }
        return res;
    }

    /**
     * 执行请求
     * @param req
     * @return
     * @throws IOException
     */
    private static String executeReq(HttpUriRequest req, CharSetEnum charSetEnum) throws IOException {

        //请求
        CloseableHttpResponse response = client.execute(req);
        //状态码
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == SUCCESS_STATUS) {
            //返回
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, charSetEnum.getCharSet());
                EntityUtils.consume(entity);
                response.close();
                return result;
            } else {
                return null;
            }

        } else {
            req.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
    }
}
